﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TinyEngine.Core.Services;
using TinyEngine.Core.Asset;
using WinFormsGraphicsDevice;
using Microsoft.Xna.Framework.Graphics;

namespace TinyEngineEditor.Explorer
{
    public partial class AssetExplorer : Window
    {
        public AssetExplorer()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(AssetExplorer_Loaded);
            treeView.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(treeView_SelectedItemChanged);
        }

        void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (treeView.SelectedItem != null)
            {
                var item = treeView.SelectedItem as TreeViewItem;
                var asset = item.Tag as SpriteAsset;

                assetRenderer.text = asset.Asset;
                assetRenderer.Invalidate();
            }
        }
        AssetRenderer assetRenderer = null;
        void AssetExplorer_Loaded(object sender, RoutedEventArgs e)
        {
            assetRenderer = new AssetRenderer();
            renderer.Load(assetRenderer);
            assetRenderer.Init();

            var assets = ServiceManager.GetService<AssetLibrary>();
            foreach (var item in assets.Sprites)
            {
                var node = new TreeViewItem()
                {
                    Header = item.Value.Name,
                    Tag = item.Value
                };
                treeView.Items.Add(node);
            }
        }
    }

    public class AssetRenderer : BasicGraphicsDeviceControl
    {
        public Texture2D text = null;
        SpriteBatch batch;
        
        public void Init()
        {
            batch = new SpriteBatch(this.GraphicsDevice);
        }

        protected override void Draw()
        {
            base.Draw();
            if(text == null) return;
            try
            {
                batch.Begin();
                batch.Draw(text, new Microsoft.Xna.Framework.Rectangle(10, 10, text.Width, text.Height), Microsoft.Xna.Framework.Color.White);
                batch.End();
            }
            catch (Exception err)
            {
                Console.Write(err.ToString());
            }
        }
    }
}
